package core;

import java.io.BufferedReader;
import java.io.FileReader;

import util.Constants;
import util.NBGStrParser;

/**
 * This method is abandoned because only indexing the points are not correct for
 * subsequent query processing.
 * 
 * @author Xiaohui
 * 
 */
public class TimsTimePartImpl {
	static int numParts = 8;
	static String prefix = "D:/Research/parinet/meta/";
	static int collectionStartTime = 0;
	static int collectionEndTime = 800;
	TimePartition[] timeParts;
	int step = (int) ((collectionEndTime - collectionStartTime) / numParts);

	public void TimsTimePartImpl() {
	}

	public void buildPartitions() throws Exception {
		timeParts = new TimePartition[numParts];
		String rtreeFile;

		for (int i = 0; i < numParts; i++) {
			rtreeFile = prefix + "timsRtree" + i;
			timeParts[i] = new TimePartition(collectionStartTime + step * i,
					collectionStartTime + step * (i + 1), rtreeFile);
		}
	}

	/**
	 * Build B-tree with data Normalized file expected.<br>
	 * 1. Distribute data into respective regions <br>
	 * 2. create b+ tree index on the regions <br>
	 * 
	 * @param normFilename
	 * @throws Exception
	 */
	public void loadData(String rawFilename) throws Exception {
		// note that disappearing data has speed ==0
		System.out
				.println("Loading data into partitions and index with RTree...");
		BufferedReader in = new BufferedReader(new FileReader(rawFilename));
		int count = 0;
		NBGStrParser parser;
		String str;
		TimePartition timep = null;
		while ((str = in.readLine()) != null) {
			if ((count % 10000) == 0)
				System.out.println("Loading progress: " + count);
			count++;
			parser = new NBGStrParser(str);
			timep = timeParts[getPartIndex(parser.getTimepoint())];
			timep.insertData(str, parser, count);
		}
		in.close();
	}

	private int getPartIndex(int timepoint) {
		return (int) (timepoint / step);
	}

	public static void main(String[] args) throws Exception {
		TimsTimePartImpl test = new TimsTimePartImpl();
		test.buildPartitions();
		test.loadData(Constants.rawDataFile);
		System.out.println("Done " + test.getPartIndex(102));
	}
}
